import axios from "axios";
import { Enum } from "@/js/enum";
import ElementUI from "element-ui";
let flag = {}
/**
 * 后端api基础公共封装
 */
export class Base {
  // 基础地址
  baseUrl = process.env.VUE_APP_BASE_URL
  // 端口；由继承类补充
  port = ""
  $axios = null
  constructor(port) {
    if (port) {
      this.port = port
    }
    this.$axios = axios.create({
      baseURL: this.baseUrl + this.port,
      timeout: 30000,// 超时 毫秒
    })
  }

  /**
   * http get 请求
   * @param path string
   * @param params object
   * @param callback function()
   * @param {object} setting  请求设置：async·异步请求，默认true、
   */
  get(path, params, callback, setting) {
    let token = JSON.parse(localStorage.getItem('token')) ?? {token:''}

    let request = {
      method: 'get',
      url: path,
      params: params,
      headers: {
        "Authorization":  token.token
      },
    }

    if (typeof setting === "object" && setting.async===false){
      return this.syncRequestV2(request, callback)
    }
    return this.request(request, callback)
  }

  /**
   * http post 请求
   * @param path string
   * @param params object
   * @param callback function()
   * @param {object} setting  请求设置：async·异步请求，默认true、
   */
  post(path, params, callback, setting) {
    let request = {
      method: 'post',
      url: path,
      data: params,
      headers: {
        "Authorization": localStorage.getItem('token') ? JSON.parse(localStorage.getItem('token')).token : '',
        "Content-Type": 'application/json',
      },
    }

    if (flag == path) {
      console.log(path);
      ElementUI.Message.error('操作过快!')
    } else {
      flag = path
      if (typeof setting === "object" && setting.async===false){
        return this.syncRequestV2(request, callback)
      }
      this.request(request, callback);
    }
  }
  filePost(path, params, data, callback) {
    this.request({
      method: 'post',
      url: path,
      params: params,
      data: data,
      headers: {
        "Authorization": JSON.parse(localStorage.getItem('token')).token,
        "Content-Type": 'multipart/form-data',
      },
    }, callback);
  }
  /**
   * http request 基础请求方法
   * @param method
   * @param url
   * @param params
   * @param callback
   */
  request(request, callback) {
    this.$axios.request(request).then(res => {
      if (res.status != 200) {
        res.data.status = false
        res.data.message = "网络错误！"

      } else if (res.data.code == Enum.CodeSuccess) {
        res.data.status = true
      } else {
        res.data.status = false
      }
      callback(res.data)
      flag = {}
    }).catch(error => {
      flag = {}
      callback(error)
      alert(`请求网络失败! 错误信息:${error.message}`)
    })
  }

  /**
   * http request 基础请求方法 同步
   * ~~~
   * 经确认无法实现同步，留档产考
   * ~~~
   * @param method
   * @param url
   * @param params
   * @param callback
   */
  async syncRequest(request, callback) {
    try {
      const res = await this.$axios.request(request);
      console.log("同步请求响应",res);
      if (res.status != 200) {
        res.data.status = false
        res.data.message = "网络错误！"
      } else if (res.data.code == Enum.CodeSuccess) {
        res.data.status = true
      } else {
        res.data.status = false
      }
      callback(res.data)
    } catch (error) {
      console.error('Error in synchronous request:', error);
      callback({status:false,message:error})
    }
  }

  /**
   * http request 基础请求方法 同步 v2
   * @param {object} request 请求对象 {url,method,headers,params,data}
   * @param {function} callback 结果回调
   */
  syncRequestV2(request, callback){
    // 默认方法
    if (!request.method){
      request.method = 'get'
    }
    // query 参数处理
    let query = ''
    let body = null
    if (typeof request.params === 'object'){
      for (let key in request.params) {
        query += '&'+encodeURIComponent(key) + '=' + encodeURIComponent(request.params[key]);
      }
      if (query !== '') {
        query = '?'+query.substring(1)
      }
    }else if (typeof request.params === 'string' && request.params){
      query = '?'+request.params
    }
    // body参数处理
    if (typeof request.data === 'object'){
      body = JSON.stringify(request.data)
    }else if (typeof request.data === 'string' && request.data){
      body = request.data
    }

    // 发送请求
    const xhr = new XMLHttpRequest();
    xhr.open(request.method, this.baseUrl+request.url+query, false);
    for (let key in request.headers){
      xhr.setRequestHeader(key, request.headers[key])
    }
    xhr.send(body);
    // 处理响应
    let res = JSON.parse(xhr.responseText)??{}
    if (!res){
      res.status = false
      res.message = xhr.responseText
      res.status = xhr.status
    }else if (res.code == '000000'){
      res.status = true
    }else{
      res.status = false
    }
    callback(res)
  }
}